<template>
  <div class="page-container">
    <a-card :bordered="false" size="small" style="margin-bottom: 10px">
      <a-row :gutter="16">
        <a-col class="search-row" :span="20">
          <a-form layout="inline">
            <a-form-item label="账号">
              <a-input
                size="small"
                v-model:value="queryParams.byUserName"
                placeholder="请输入"
                allow-clear
                @keyup.enter="handleSearch"
              >
              </a-input>
            </a-form-item>
            <a-form-item label="姓名">
              <a-input
                size="small"
                v-model:value="queryParams.byRealName"
                placeholder="请输入"
                allow-clear
                @keyup.enter="handleSearch"
              >
              </a-input>
            </a-form-item>
            <a-form-item label="手机号">
              <a-input
                size="small"
                v-model:value="queryParams.byMobile"
                placeholder="请输入"
                allow-clear
                @keyup.enter="handleSearch"
              >
              </a-input>
            </a-form-item>
            <a-form-item label="部门">
              <a-select
                size="small"
                v-model:value="queryParams.byDepartmentId"
                placeholder="请输入"
                allow-clear
                show-search
                :options="deptList"
                :filter-option="filterOption"
                :field-names="{ label: 'departmentName', value: 'id' }"
                style="width: 200px"
                @change="handleSearch"
              >
              </a-select>
            </a-form-item>
            <a-form-item label="状态">
              <a-select
                size="small"
                v-model:value="queryParams.status"
                allow-clear
                placeholder="请选择"
                style="width: 80px"
                @change="handleSearch"
              >
                <a-select-option value="正常">正常</a-select-option>
                <a-select-option value="禁用">禁用</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" size="small" @click="handleSearch">查询</a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col class="search-row right-btn-container" :span="4">
          <a-button type="primary" size="small" @click="handleCreate">新增</a-button>
        </a-col>
      </a-row>
    </a-card>

    <a-table
      :dataSource="dataSource"
      :scroll="{ x: 'max-content' }"
      :columns="columns"
      :pagination="{ pageSize: 15 }"
      size="small"
    >
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'status'">
          <a-tag
            v-if="record.status === '正常'"
            style="cursor: pointer"
            color="green"
            @click="handleChangeStatus(record)"
            >{{ record.status }}</a-tag
          >
          <a-tag
            v-if="record.status === '禁用'"
            style="cursor: pointer"
            color="orange"
            @click="handleChangeStatus(record)"
            >{{ record.status }}</a-tag
          >
        </template>
        <!--<template v-if="column.dataIndex === 'departmentName'">-->
        <!--  <a-tooltip>-->
        <!--    <template #title>prompt text</template>-->
        <!--    {{ record.departmentName }}-->
        <!--  </a-tooltip>-->
        <!--</template>-->
        <template v-if="column.dataIndex === 'operation'">
          <a
            style="margin-right: 10px"
            @click="handleEdit(record)"
            v-if="record.userName !== 'SAdmin'"
            >修改</a
          >
          <a
            style="margin-right: 10px; color: red"
            @click="handleResetPassword(record)"
            v-if="
              userStore.userInfo.isAdministrator === '是' &&
              record.userName !== 'SAdmin' &&
              record.id !== userStore.userInfo.id
            "
            >重置密码</a
          >
        </template>
      </template>
    </a-table>

    <!--<a-pagination-->
    <!--  v-model:current="queryParams.page"-->
    <!--  v-model:page-size="queryParams.limit"-->
    <!--  style="margin-top: 20px"-->
    <!--  hideOnSinglePage-->
    <!--  showSizeChanger-->
    <!--  :total="total"-->
    <!--  show-less-items-->
    <!--  size="small"-->
    <!--  @change="getList"-->
    <!--/>-->

    <a-modal v-model:open="visible" :title="title" width="400px" @ok="handleOk">
      <a-form
        ref="formRef"
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        autocomplete="off"
      >
        <a-form-item
          label="账号"
          name="username"
          :rules="[{ required: true, message: '请输入账号!' }]"
        >
          <a-input v-model:value="form.username" size="small" :disabled="title !== '新增'" />
        </a-form-item>
        <a-form-item
          label="姓名"
          name="realName"
          :rules="[{ required: true, message: '请输入姓名!' }]"
        >
          <a-input v-model:value="form.realName" size="small" />
        </a-form-item>
        <a-form-item
          label="手机号"
          name="mobile"
          :rules="[{ required: true, validator: checkMobile }]"
        >
          <a-input v-model:value="form.mobile" size="small" />
        </a-form-item>
        <a-form-item
          label="部门"
          name="departmentId"
          :rules="[{ required: true, message: '请选择部门!' }]"
        >
          <a-select
            v-model:value="form.departmentId"
            size="small"
            :options="deptList"
            @change="handleChangeDept"
            :disabled="title === '编辑' && userStore.userInfo.userName !== 'SAdmin'"
            :field-names="{ label: 'departmentName', value: 'id' }"
          />
        </a-form-item>
        <a-form-item
          label="管理员"
          name="isAdministrator"
          :rules="[{ required: true, message: '请选择是否是管理员!' }]"
        >
          <a-select
            v-model:value="form.isAdministrator"
            size="small"
            :disabled="isAdminDisabled"
            :options="[{ value: '是' }, { value: '否' }]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { userColumns as columns } from '@/config/columns'
import { message, Modal } from 'ant-design-vue'
import {
  createOrUpdateUserApi,
  getDeptListApi,
  getUserListApi,
  resetPasswordApi,
  setUserStatusApi
} from '@/api/user'
import { createUuid } from '@/utils/encryp'
import useUserStore from '@/stores/user'

const userStore = useUserStore()
const formRef = ref()
const dataSource = ref([])
const total = ref(0)
const queryParams = reactive({
  status: undefined,
  page: 1,
  pageSize: 20,
  byUserName: undefined,
  byRealName: undefined,
  byMobile: undefined,
  byDepartmentId: undefined
})
const form = reactive({})
const visible = ref(false)
const title = ref('新增')
const deptList = ref([])
const isAdminDisabled = computed(() => {
  let res = false
  if (form.departmentId && deptList.value.length) {
    let dept = deptList.value.find((item) => item.id === form.departmentId)
    if (dept) {
      if (dept.departmentName === '管理员组' || dept.departmentName === '管理员组') {
        res = true
      }
    }
  }
  return res
})

const filterOption = (input, option) => {
  console.log(input, option)
  return option.departmentName.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
const checkMobile = (_rule, value) => {
  if (value === '') {
    return Promise.reject('请输入手机号')
  } else {
    // 校验强密码 ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
    const objRegExp = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (objRegExp.test(value)) {
      return Promise.resolve()
    } else {
      return Promise.reject('请输入正确的手机号')
    }
  }
}

const handleChangeDept = (val, dept) => {
  if (dept.departmentName === '管理员组' || dept.departmentName === '管理员组') {
    isAdminDisabled.value = true
    form.isAdministrator = '是'
  } else {
    isAdminDisabled.value = false
  }
}

const handleChangeStatus = (row) => {
  if (row.id === userStore.userInfo.id) {
    message.error('不能禁用自己')
    return
  }
  Modal.confirm({
    title: '提示',
    content: `确认${row.status === '正常' ? '禁用' : '恢复'}用户吗?`,
    onOk: () => {
      setUserStatusApi({ userID: row.id, status: row.status === '正常' ? '禁用' : '正常' }).then(
        () => {
          message.success('操作成功')
          // row.status = row.status === '正常' ? '禁用' : '正常'
          getList()
        }
      )
    }
  })
}

const getList = () => {
  let params = {
    status: queryParams.status,
    page: 1,
    pageSize: 20
  }
  if (queryParams.byUserName) {
    params.byUserName = queryParams.byUserName.trim()
  }
  if (queryParams.byRealName) {
    params.byRealName = queryParams.byRealName.trim()
  }
  if (queryParams.byMobile) {
    params.byMobile = queryParams.byMobile.trim()
  }
  if (queryParams.byDepartmentId) {
    params.byDepartmentId = queryParams.byDepartmentId.trim()
  }

  getUserListApi(params).then((res) => {
    total.value = res.totleCount
    dataSource.value = res.users
  })
}

const getDeptList = () => {
  getDeptListApi(queryParams).then((res) => {
    deptList.value = res.items
  })
}
const handleSearch = () => {
  queryParams.page = 1
  getList()
}
const handleCreate = () => {
  visible.value = true
  title.value = '新增'
  form.id = ''
  form.username = ''
  form.realName = ''
  form.departmentId = ''
  form.mobile = ''
  form.isAdministrator = ''
}
const handleEdit = (row) => {
  visible.value = true
  title.value = '编辑'
  form.id = row.id
  form.username = row.userName
  form.realName = row.realName
  form.departmentId = row.departmentId
  form.isAdministrator = row.isAdministrator
  form.mobile = row.mobile
}
const handleResetPassword = (row) => {
  Modal.confirm({
    title: '提示',
    content: `确认重置密码?`,
    onOk: () => {
      resetPasswordApi({
        userId: row.id
      })
        .then(() => {
          message.success('操作成功')
        })
        .catch(() => {
          message.error('操作失败')
        })
    }
  })
}
const handleOk = () => {
  formRef.value
    .validateFields()
    .then(() => {
      let params = {
        UserName: form.username,
        RealName: form.realName,
        DepartmentId: form.departmentId,
        IsAdministrator: form.isAdministrator,
        Mobile: form.mobile,
        Status: '正常'
      }
      if (title.value === '新增') {
        params.Id = createUuid()
      } else {
        params.Id = form.id
      }
      createOrUpdateUserApi(params).then(() => {
        message.success('操作成功')
        visible.value = false
        getList()
      })
    })
    .catch(() => {})
}

onMounted(() => {
  handleSearch()
  getDeptList()
})
</script>

<style lang="less" scoped></style>
